import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.KeyEvent;

import com.speljohan.rsbot.bot.Bot;
import com.speljohan.rsbot.event.events.ServerMessageEvent;
import com.speljohan.rsbot.event.listeners.PaintListener;
import com.speljohan.rsbot.event.listeners.ServerMessageListener;
import com.speljohan.rsbot.script.Constants;
import com.speljohan.rsbot.script.Methods;
import com.speljohan.rsbot.script.Script;
import com.speljohan.rsbot.script.Skills;
import com.speljohan.rsbot.script.wrappers.RSInterface;
import com.speljohan.rsbot.script.wrappers.RSItemTile;
import com.speljohan.rsbot.script.wrappers.RSObject;
import com.speljohan.rsbot.script.wrappers.RSPlayer;
import com.speljohan.rsbot.script.wrappers.RSTile;
import com.speljohan.rsbot.script.wrappers.RSTilePath;

public class DragginYews extends Script implements PaintListener,
		ServerMessageListener {

	RSTile[] treeLocs = new RSTile[] { new RSTile(2758, 3434),
			new RSTile(2760, 3428), new RSTile(2761, 3432),
			new RSTile(2756, 3431), new RSTile(2755, 3434),
			new RSTile(2766, 3428) };

	private final int[] nestIds = { 5070, 5071, 5072, 5073, 5074, 5075, 5076,
			7413, 11966 };

	int[] axeID = new int[] { 1351, 1349, 1353, 1361, 1355, 1357, 1359, 6739,
			13470 };
	int[] yewTree = new int[] { 1309, 8503, 8504, 8505, 8506, 8507, 8508, 8509,
			8510, 8511, 8512, 8513 };
	int lastTreeIndex;
	Color BG = new Color(0, 0, 0, 100);

	private final RSTile[] bankToTrees = new RSTile[] { new RSTile(2808, 3440),
			new RSTile(2805, 3433), new RSTile(2796, 3433),
			new RSTile(2783, 3432), new RSTile(2771, 3430),
			new RSTile(2763, 3429) };

	RSTile[] treesToBank = reversePath(bankToTrees);
	RSTilePath bank2Trees = new RSTilePath(randomizePath(bankToTrees, 2, 2),
			this);
	RSTilePath trees2Bank = new RSTilePath(randomizePath(treesToBank, 2, 2),
			this);

	long avoidedCombat;
	long lastCheck;
	int checkTime;
	int bankID = 2213;
	int yewsCut;
	long didAntiBan;
	int waitAfterMoving = -1;
	int failCount = 0;
	int Nest = 0;
	int previousSpeed;
	int treeID = 1309;
	int lastExp;
	int chopped;
	int startingLevel = 0;
	int startingExperience = 0;
	int wait1 = 400, wait2 = 700;
	int currenttab;
	Point mousePos;
	int randomInt;
	int GambleInt, rambleInt;
	long lastcheck1 = -1, lastCheck2, lastCheck3 = System.currentTimeMillis();
	long timer = System.currentTimeMillis();
	int checkTime1 = random(240000, 480000);
	public String[] thingsToSayIdle = new String[] { "" };
	int woodcutting;
	int new8;
	int index8 = Skills.getStatIndex("woodcutting");

	public long startTime = System.currentTimeMillis();

	public boolean activateCondition() {
		antiban();
		check();
		return false;
	}

	void antiban() {
		GambleInt = random(1, 25);
		if (!bank.getInterface().isValid()) {
			if (GambleInt == 1) {
				turnCamera();
				wait(random(300, 500));
			}
			if (GambleInt == 2) {
				final int xA = random(0, 750);
				final int yA = random(0, 500);
				mousePos = getMouseLocation();
				moveMouse(xA, yA);
				wait(random(300, 500));
				moveMouse(mousePos, 7, 7);
				wait(random(100, 200));
				turnCamera();
				wait(random(300, 500));

			}
			if (GambleInt == 3) {
				if (getCurrentTab() != Constants.TAB_INVENTORY) {
					currenttab = getCurrentTab();
					openTab(Constants.TAB_INVENTORY);
					wait(random(300, 500));
					turnCamera();
					wait(random(300, 500));
				}
			}
			if (GambleInt == 4) {
				mousePos = getMouseLocation();
				final RSPlayer p = getNearestPlayerByLevel(120, 138);
				if (p != null) {
					moveMouse(p.getScreenLocation(), 5, 5);
					wait(random(300, 500));
					clickMouse(false);
					wait(random(1000, 1500));
					moveMouse(mousePos, 7, 7);
					wait(random(100, 200));
				}
			}
			if (GambleInt == 5) {
				turnCamera();
				wait(random(300, 500));
				final int xA = random(0, 750);
				final int yA = random(0, 500);
				mousePos = getMouseLocation();
				moveMouse(xA, yA);
				wait(random(300, 500));
				moveMouse(mousePos, 7, 7);
				wait(random(100, 200));
			}
			if (GambleInt == 6) {
				turnCamera();
				wait(random(300, 500));
			}
			if (GambleInt == 7) {
				mousePos = getMouseLocation();
				currenttab = getCurrentTab();
				openTab(random(0, 1));
				wait(random(300, 500));
				openTab(currenttab);
				wait(random(300, 500));
				moveMouse(mousePos, 7, 7);
				wait(random(100, 200));
			}
			if (GambleInt == 8) {
				mousePos = getMouseLocation();
				moveMouse(random(0, 450), random(0, 450));
				wait(random(300, 500));
				moveMouse(mousePos, 7, 7);
				wait(random(100, 200));
			}
			if (System.currentTimeMillis() - lastCheck2 >= checkTime) {
				lastCheck2 = System.currentTimeMillis();
				checkTime = random(300000, 600000);
				turnCamera();
				wait(random(300, 500));
				mousePos = getMouseLocation();
				currenttab = getCurrentTab();
				openTab(random(0, 13));
				wait(random(300, 500));
				turnCamera();
				wait(random(300, 500));
				openTab(currenttab);
				wait(random(300, 500));
				moveMouse(mousePos, 7, 7);
				wait(random(100, 200));
			}
		}
	}

	void antiban1() {

		if (System.currentTimeMillis() - lastCheck3 >= checkTime1) {
			lastCheck3 = System.currentTimeMillis();
			checkTime1 = random(240000, 480000);
			mousePos = getMouseLocation();
			currenttab = getCurrentTab();
			new8 = skills.getCurrentSkillExp(index8);
			if (getCurrentTab() != Constants.TAB_STATS) {
				openTab(Constants.TAB_STATS);
			}
			log("We are training woodcutting");
			moveMouse(random(664, 709), random(355, 382));
			wait(random(1000, 2000));
			openTab(currenttab);
			wait(random(300, 500));
			moveMouse(mousePos, 7, 7);
			wait(random(300, 500));
		}
	}

	public void check() {

		final long currentTime = System.currentTimeMillis();
		if (lastCheck == -1) {
			woodcutting = skills.getCurrentSkillExp(index8);
			lastCheck = 1;
		}
		if ((currentTime - lastcheck1) / 60000 >= 1) {
			lastcheck1 = System.currentTimeMillis();
			lastCheck = -1;
		}
	}

	public int closestTree(final RSTile[] tiles) {
		int closest = -1;
		for (int i = 0; i < tiles.length; i++) {
			final RSTile tile = tiles[i];
			if (getObjectAt(tile) != null) {
				if (closest == -1 && isTree(getObjectAt(tile).getID())) {
					closest = i;
					continue;
				}
				if (closest == -1) {
					continue;
				}
				if (isTree(getObjectAt(tile).getID())
						&& distanceTo(getObjectAt(tile)) < distanceTo(getObjectAt(tiles[closest]))) {
					closest = i;
				}
			}
		}
		return closest;
	}

	@Override
	public String getAuthor() {
		return "Draggin";
	}

	@Override
	public String getName() {
		return "Draggin's Yew's";
	}

	@Override
	public String getScriptCategory() {
		return "Woodcutting";
	}

	@Override
	public String getScriptDescription() {
		String html = "";

		html += "<html>\n";
		html += "<body>";
		html += "<h1><font size=\"4\" color=\"blue\" Draggin's Yews</h1><br>";

		html += "<font size=\"4\" color=\"blue\"Chops Yew trees in Catherby and then banks them! :P<br><br>";
		html += "<font size=\"4\" color=\"blue\"<ul><b>Features:</b>";
		html += "<font size=\"4\" color=\"blue\"<li>Fast tree switching!</li>";
		html += "<font size=\"4\" color=\"blue\"<li>Flawless nest picking up!</li>";
		html += "<font size=\"4\" color=\"blue\"<li>Use your own antiban</li>";
		html += "<font size=\"4\" color=\"blue\"<li>Axe Can Be Equipped or In Inventory</li>";
		html += "<font size=\"4\" color=\"blue\"<li>Handles Combat</li>";
		html += "</ul>";
		html += "</body>";
		html += "</html>";

		return html;
	}

	@Override
	public double getVersion() {
		return 11;
	}

	public boolean isTree(final int treeID) {
		for (final int id : yewTree) {
			if (id == treeID) {
				return true;
			}
		}
		return false;
	}

	public boolean isWelcomeButton() {
		final RSInterface welcomeInterface = RSInterface.getInterface(378);
		if (welcomeInterface.getChild(45).getAbsoluteX() > 20
				|| !welcomeInterface.getChild(117).getText().equals(
						"10.1120.190")
				&& !welcomeInterface.getChild(117).getText().equals("")) {
			log("We still are in Welcome Screen");
			return true;
		} else {
			return false;
		}
	}

	@Override
	public int loop() {
		try {
			final RSObject bankBooth = findObject(bankID);
			antiban();
			setMaxAltitude();
			nest();
			if (getEnergy() > random(60, 100)) {
				setRun(true);
			}
			if (getMyPlayer().isInCombat() && !getMyPlayer().isMoving()) {
				log("In combat, attempting to run..");
				runAway();
				return random(400, 700);
			}
			if (!isInventoryFull()
					&& Methods.distanceBetween(getMyPlayer().getLocation(),
							treeLocs[3]) > 15) {
				try {
					bank2Trees.walkToEnd();
				} catch (final Exception e) {
				}
			}
			if (isInventoryFull()
					&& Methods.distanceBetween(getMyPlayer().getLocation(),
							new RSTile(2808, 3440)) > 5) {
				try {
					trees2Bank.walkToEnd();

				} catch (final Exception e) {
				}
			}

			if (Methods.distanceBetween(getMyPlayer().getLocation(),
					new RSTile(2808, 3440)) <= 5) {
				if (isInventoryFull()) {
					if (tileOnScreen(bankBooth.getLocation())) {
						atObject(bankBooth, "use-quickly");
						wait(random(1000, 2000));
					}
					if (bank.getInterface().isValid()) {
						try {
							bank.depositAllExcept(axeID);
						} catch (final Exception e) {
						}
						bank.close();
					}
				}
				if (!isInventoryFull()) {
					try {
						bank2Trees.walkToEnd();
						antiban();
					} catch (final Exception e) {
					}
				}
				return random(200, 400);
			}

			if (Methods.distanceBetween(getMyPlayer().getLocation(),
					treeLocs[3]) <= 15) {
				if (!isInventoryFull()) {
					final int treeIndex = closestTree(treeLocs);
					if (treeIndex != -1
							&& distanceTo(treeLocs[treeIndex]) <= 14) {
						if (inventoryContains(1511)) {
							if (getMyPlayer().getAnimation() != -1
									&& lastTreeIndex == treeIndex) {
								return random(100, 200);
							}
						}
						lastTreeIndex = treeIndex;
						if (tileOnScreen(treeLocs[treeIndex])
								&& getMyPlayer().getAnimation() == -1) {
							atTile(treeLocs[treeIndex], "chop");
							antiban();
							return random(500, 1000);
						}
						if (getMyPlayer().getAnimation() == -1) {
							walkTileMM(new RSTile(treeLocs[treeIndex].getX(),
									treeLocs[treeIndex].getY() - 1));
						}
						return random(350, 700);
					}
				}
				if (isInventoryFull()) {
					try {
						trees2Bank.walkToEnd();
					} catch (final Exception e) {
					}
				}
			}
		} catch (final Exception e) {
		}

		return random(500, 1000);
	}

	public void nest() {
		final RSItemTile nest = getGroundItemByID(nestIds);
		if (nest != null) {
			log("Found nest");
			atTile(nest, "Take");
			Nest++;
		}
	}

	@Override
	public void onFinish() {
		Bot.getEventManager().removeListener(ServerMessageListener.class, this);
	}

	public void onRepaint(final Graphics g) {
		if (isLoggedIn()) {
			long millis = System.currentTimeMillis() - startTime;
			if (lastExp == 0) {
				lastExp = skills.getCurrentSkillExp(Constants.STAT_WOODCUTTING);
			}

			if (skills.getCurrentSkillExp(Constants.STAT_WOODCUTTING) > lastExp) {
				lastExp = skills.getCurrentSkillExp(Constants.STAT_WOODCUTTING);
				chopped++;
			}

			if (startingLevel == 0 || startingExperience == 0) {
				startingLevel = skills
						.getCurrentSkillLevel(Constants.STAT_WOODCUTTING);
				startingExperience = skills
						.getCurrentSkillExp(Constants.STAT_WOODCUTTING);
			}
			final long hours = millis / (1000 * 60 * 60);
			millis -= hours * 1000 * 60 * 60;
			final long minutes = millis / (1000 * 60);
			millis -= minutes * 1000 * 60;
			final long seconds = millis / 1000;
			final int topX = 515 - 173, topY = 340 - 80, x = topX + 5;
			int y = topY + 5;
			g.setColor(BG);
			g.fill3DRect(topX, topY, 515 - topX, 340 - topY, true);
			g.setColor(Color.cyan);
			g.drawString(getName(), x, y += 13);
			g.drawString("Runtime: " + hours + "h " + minutes + "min "
					+ seconds + "sec.", x, y += 13);
			g.drawString("Yews chopped:: " + yewsCut, x, y += 13);
			g
					.drawString(
							"Gained "
									+ (skills
											.getCurrentSkillLevel(Constants.STAT_WOODCUTTING) - startingLevel)
									+ " levels", x, y += 13);
			g.drawString(skills.getXPToNextLevel(Constants.STAT_WOODCUTTING)
					+ " XP to next level.", x, y += 13);
		}
	}

	@Override
	public boolean onStart(final String[] args) {
		try {
			log("Draggin's Yew's");
			log("----------------------------");
			log("The future of Yew scripts!");
			log("But behold, The Future is here");
			log("Welcome to... Draggin's Yew's");
			log("/--------------------------");

			log("D");
			wait(random(30, 60));
			log("Dr");
			wait(random(30, 60));
			log("Dra");
			wait(random(30, 60));
			log("Drag");
			wait(random(30, 60));
			log("Dragg");
			wait(random(30, 60));
			log("Draggi");
			wait(random(30, 60));
			log("Draggin");
			wait(random(30, 60));
			log("Draggin Y");
			wait(random(30, 60));
			log("Draggin Ye");
			wait(random(30, 60));
			log("Draggin Yew");
			wait(random(30, 60));
			log("Draggin Yews");
			wait(random(30, 60));
			log("Draggin Yews H");
			wait(random(30, 60));
			log("Draggin Yews Ha");
			wait(random(30, 60));
			log("Draggin Yews Has");
			wait(random(30, 60));
			log("Draggin Yews Has N");
			wait(random(30, 60));
			log("Draggin Yews Has No");
			wait(random(30, 60));
			log("Draggin Yews Has Now");
			wait(random(30, 60));
			log("Draggin Yews Has Now B");
			wait(random(30, 60));
			log("Draggin Yews Has Now Be");
			wait(random(30, 60));
			log("Draggin Yews Has Now Bee");
			wait(random(30, 60));
			log("Draggin Yews Has Now Been");
			wait(random(30, 60));
			log("Draggin Yews Has Now Been I");
			wait(random(30, 60));
			log("Draggin Yews Has Now Been In");
			wait(random(30, 60));
			log("Draggin Yews Has Now Been Ini");
			wait(random(30, 60));
			log("Draggin Yews Has Now Been Init");
			wait(random(30, 60));
			log("Draggin Yews Has Now Been Initi");
			wait(random(30, 60));
			log("Draggin Yews Has Now Been Initia");
			wait(random(30, 60));
			log("Draggin Yews Has Now Been Initial");
			wait(random(30, 60));
			log("Draggin Yews Has Now Been Initiali");
			wait(random(30, 60));
			log("Draggin Yews Has Now Been Initializ");
			wait(random(30, 60));
			log("Draggin Yews Has Now Been Initialize");
			wait(random(30, 60));
			log("Draggin Yews Has Now Been Initialized");
			wait(random(30, 60));
			log("Draggin Yews Has Now Been Initialized,");
			wait(random(30, 60));
			log("Draggin Yews Has Now Been Initialized, T");
			wait(random(30, 60));
			log("Draggin Yews Has Now Been Initialized, TY");
			wait(random(30, 60));
			log("Seagulls FTW!");
			wait(random(30, 60));
		} catch (final Exception e) {

		}

		return true;
	}

	public void runAway() {
		RSTile drag, bar;
		drag = getMyPlayer().getLocation();
		setRun(true);

		bar = new RSTile(drag.getX() + random(10, 12), drag.getY()
				+ random(10, 12));

		walkTileMM(bar);
		while (getMyPlayer().isMoving()) {
			wait(random(2000, 4000));
		}
		wait(random(3000, 5000));
		walkTileMM(drag);
	}

	public void serverMessageRecieved(final ServerMessageEvent e) {
		if (e.getMessage().contains("You get some yew logs.")) {
			yewsCut++;
		}
	}

	public void setMaxAltitude() {
		Bot.getInputManager().pressKey((char) 38);
		wait(random(500, 1000));
		Bot.getInputManager().releaseKey((char) 38);
	}

	public void turnCamera() {
		final char[] LR = new char[] { KeyEvent.VK_LEFT, KeyEvent.VK_RIGHT };
		final char[] UD = new char[] { KeyEvent.VK_DOWN, KeyEvent.VK_UP };
		final char[] LRUD = new char[] { KeyEvent.VK_LEFT, KeyEvent.VK_RIGHT,
				KeyEvent.VK_UP, KeyEvent.VK_UP };
		final int random2 = random(0, 2);
		final int random1 = random(0, 2);
		final int random4 = random(0, 4);

		if (random(0, 3) == 0) {
			Bot.getInputManager().pressKey(LR[random1]);
			try {
				Thread.sleep(random(100, 400));
			} catch (final Exception e) {
			}
			Bot.getInputManager().pressKey(UD[random2]);
			try {
				Thread.sleep(random(300, 600));
			} catch (final Exception e) {
			}
			Bot.getInputManager().releaseKey(UD[random2]);
			try {
				Thread.sleep(random(100, 400));
			} catch (final Exception e) {
			}
			Bot.getInputManager().releaseKey(LR[random1]);
		} else {
			Bot.getInputManager().pressKey(LRUD[random4]);
			if (random4 > 1) {
				try {
					Thread.sleep(random(300, 600));
				} catch (final Exception e) {
				}
			} else {
				try {
					Thread.sleep(random(500, 900));
				} catch (final Exception e) {
				}
			}
			Bot.getInputManager().releaseKey(LRUD[random4]);
		}
	}

}